#include "stm32f10x.h"                  // Device header

int16_t Increment;

/**
  * @brief		初始化对射红外计数传感器，注意GPIO和AFIO的时钟开启
  * @parm		无
  * @retval		无
  */
void Encoder_Init(void)
{
	//初始化GPIO
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);		//开启时钟
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;				//上拉输入
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1;		//B0 & B1
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;	
	GPIO_Init(GPIOB, &GPIO_InitStructure);
	
	//初始化AFIO	函数定义在gpio.h
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);		//开启时钟，外部中断必须开启AFIO时钟
	//将指定GPIO的指定引脚映射为中断引脚
	GPIO_EXTILineConfig(GPIO_PortSourceGPIOB, GPIO_PinSource0);
	GPIO_EXTILineConfig(GPIO_PortSourceGPIOB, GPIO_PinSource1);
	
	//初始化EXTI	函数定义在exti.h
	EXTI_InitTypeDef EXTI_InitStructure;
	EXTI_InitStructure.EXTI_Line = EXTI_Line0 | EXTI_Line1;				//中断引脚	
	EXTI_InitStructure.EXTI_LineCmd = ENABLE;				//使能开关	
	EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;		//中断触发
	EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;	//下降沿触发
	EXTI_Init(&EXTI_InitStructure);
	
	//中断优先级分组	函数定义在misc.h
	//抢占分组2，响应分组2
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
	
	//初始化NVIC	函数定义在misc.h
	NVIC_InitTypeDef NVIC_InitStructure;
	NVIC_InitStructure.NVIC_IRQChannel = EXTI0_IRQn;		//IRQ通道
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;				//使能开关
	//因为中断优先级分组为2，即各自2位，表示范围0~3
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;	//抢占优先级1
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;			//响应优先级1
	NVIC_Init(&NVIC_InitStructure);
	
	NVIC_InitStructure.NVIC_IRQChannel = EXTI1_IRQn;		//IRQ通道
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;				//使能开关
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;	//抢占优先级1
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2;			//响应优先级2
	NVIC_Init(&NVIC_InitStructure);
}

/**
  * @brief		获取旋钮变化值
  * @parm		无
  * @retval		变化值	范围：-32768 ~ 32767
  */
int16_t Encoder_GetIncrement(void)
{
	int16_t Temp = Increment;
	Increment = 0;
	return Temp;
}


//中断处理函数		定义在startup...h启动文件
void EXTI0_IRQHandler(void)
{
	if(EXTI_GetITStatus(EXTI_Line0) == SET)
	{
		//正转
		if(GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_1) == 1)
			Increment++;
		EXTI_ClearFlag(EXTI_Line0);
	}
}

//中断处理函数		定义在startup...h启动文件
void EXTI1_IRQHandler(void)
{
	if(EXTI_GetITStatus(EXTI_Line1) == SET)
	{
		//正转
		if(GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_0) == 1)
			Increment--;
		EXTI_ClearFlag(EXTI_Line1);
	}
	
}


